package com.ydzc.web.util;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

public class StringUtils {
    private StringUtils() {
    }

    /**
     * 检查指定的字符串是否为空。
     * <ul>
     * <li>SysUtils.isEmpty(null) = true</li>
     * <li>SysUtils.isEmpty("") = true</li>
     * <li>SysUtils.isEmpty("   ") = true</li>
     * <li>SysUtils.isEmpty("abc") = false</li>
     * </ul>
     *
     * @param value 待检查的字符串
     * @return true/false
     */
    public static boolean isEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isEmpty(String[] value) {
        boolean flag = true;
        if (value != null && value.length > 0) {
            flag = false;
        }
        return flag;
    }

    /**
     * 检查对象是否为数字型字符串,包含负数开头的。
     */
    public static boolean isNumeric(Object obj) {
        if (obj == null) {
            return false;
        }
        char[] chars = obj.toString().toCharArray();
        int length = chars.length;
        if (length < 1)
            return false;

        int i = 0;
        if (length > 1 && chars[0] == '-')
            i = 1;

        for (; i < length; i++) {
            if (!Character.isDigit(chars[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查指定的字符串列表是否不为空。
     */
    public static boolean areNotEmpty(String... values) {
        boolean result = true;
        if (values == null || values.length == 0) {
            result = false;
        } else {
            for (String value : values) {
                result &= !isEmpty(value);
            }
        }
        return result;
    }

    /**
     * 把通用字符编码的字符串转化为汉字编码。
     */
    public static String unicodeToChinese(String unicode) {
        StringBuilder out = new StringBuilder();
        if (!isEmpty(unicode)) {
            for (int i = 0; i < unicode.length(); i++) {
                out.append(unicode.charAt(i));
            }
        }
        return out.toString();
    }

    public static String toUnderlineStyle(String name) {
        StringBuilder newName = new StringBuilder();
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    newName.append("_");
                }
                newName.append(Character.toLowerCase(c));
            } else {
                newName.append(c);
            }
        }
        return newName.toString();
    }

    public static String convertString(byte[] data, int offset, int length) {
        if (data == null) {
            return null;
        } else {
            try {
                return new String(data, offset, length, "UTF-8");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static byte[] convertBytes(String data) {
        if (data == null) {
            return null;
        } else {
            try {
                return data.getBytes("UTF-8");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String bufferedReaderToString(BufferedReader bufferedReader) throws IOException {
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }
    /**
     * @param date
     * @param moudle {yyyy-MM-dd HH:mm:ss,yyyyMMddHHmmss....}
     * @return
     */
    public static String dateToStr(Date date, String moudle) {
        if(isEmpty(moudle)){
            moudle="yyyy-MM-dd";
        }
        date = (date != null ? date : new Date());
        SimpleDateFormat formatter = new SimpleDateFormat(moudle);
        return formatter.format(date);
    }

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent().trim());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            throw ex;
        }

    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            if (isNumeric(value)) {
                filed.appendChild(document.createTextNode(value));
            } else {
                filed.appendChild(document.createCDATASection(value));
            }
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }
    //第一步，设所有发送或者接收到的数据为集合M，将集合M内非空参数值的参数按照参数名ASCII码从小到大排序（字典序），使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串stringA。
    //特别注意以下重要规则：
    //参数名ASCII码从小到大排序（字典序）；

    /**
     * @param map
     * @return 返回URL键值对的格式（即key1=value1&key2=value2…）
     * @throws IOException
     */
    public static String urlKeyValue(Map<String, String> map) throws IOException {
        Set<String> keySet = map.keySet();
        Iterator<String> iterator = keySet.iterator();
        //字典排序
        ArrayList<String> list = new ArrayList<String>();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if (StringUtils.areNotEmpty(map.get(key))) {
                list.add(key + "=" + map.get(key));
            }
        }
        Collections.sort(list);
        String temp = "";
        for (int i = 0; i < list.size(); i++) {
            temp = temp + "&" + list.get(i);
        }
        return temp.substring(1, temp.length());
    }

    /**
     * @param str     要加密的字符串
     * @param encrypt 加密的方式 MD5 SHA1
     * @return sha1加密之后的字符串, 默认返回SHA1加密的字符串
     */
    public static String getEncrypt(String str, String encrypt) {
        if (str == null || str.length() == 0) {
            return null;
        }
        if (encrypt == null || encrypt.length() == 0) {
            encrypt = "SHA1";
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(encrypt);
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

    public static String uuidStr(Integer... length) {
        if (!(length.length > 0 && length[0] > 8)) {
            return UUID.randomUUID().toString().replaceAll("-", "").substring(16);
        } else {
            return UUID.randomUUID().toString().replaceAll("-", "").substring(length[0]);
        }
    }

    public static String arryToString(String[] arry) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arry.length; i++) {
            sb.append(arry[i] + ",");
        }
        String str = sb.toString();
        return str.substring(0, str.length() - 1);

    }

    /**
     *
     * @return 返回长度为4的随机数
     */
    public static String randomIntValue(){
        int max = 9999;
        int min = 1000;
        int code = new Random().nextInt(max) % (max - min + 1) + min;
        return code+"";
    }


}
